<template>
  <div>
    <h1>订单列表</h1>

    <div>
      <el-form :inline="true" :model="searchData" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="searchData.keyWord"
            placeholder="商品名称/ID/关键词"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态" style="width: 250px">
          <el-select
            v-model="searchData.status"
            placeholder="请选择订单状态"
            clearable
          >
            <el-option label="待支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="已发货" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型" style="width: 250px">
          <el-select
            v-model="searchData.type"
            placeholder="请选择订单类型"
            clearable
          >
            <el-option
              v-for="item in orderTypeList"
              :label="item.dictName"
              :value="item.dictValue"
              :key="item.dictId"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getOrderList()">查询</el-button>
          <el-button type="primary" @click="onAddOrder()">添加订单</el-button>
          <el-button type="primary" @click="onExportOrder()">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="orderId" label="ID" />
      <el-table-column prop="orderNo" label="订单编号" />
      <el-table-column prop="prodInfo" label="商品信息" />
      <el-table-column prop="orderAmount" label="订单金额" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column
        prop="orderType"
        label="订单类型"
        :formatter="formatter"
      />
      <el-table-column label="商品图片">
        <template #default="scope">
          <img
            v-for="item in scope.row.imageList"
            :src="item"
            width="50px"
            height="50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <el-tag v-if="scope.row.orderStatus == 0">未支付</el-tag>
          <el-tag v-if="scope.row.orderStatus == 1">已支付</el-tag>
          <el-tag v-if="scope.row.orderStatus == 2">待支付</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            @click="handleViewOrder(scope.row)"
            size="small"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchData.pageNum"
          v-model:page-size="searchData.pageSize"
          :page-sizes="[2, 3, 4, 5]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="700">
        <el-form :model="form">
          <el-form-item label="选择商品" :label-width="formLabelWidth">
            <el-select v-model="form.infoId" placeholder="请选择商品">
              <el-option
                v-for="item in ProInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" :label-width="formLabelWidth">
            <el-input v-model="form.buyNum" autocomplete="off" />
          </el-form-item>
          <div>
            <el-button type="primary" @click="addProdInfo()">添加</el-button>
          </div>
          <div>
            <el-table :data="buyInfoList" stripe style="width: 100%">
              <el-table-column prop="prodId" label="商品Id" />
              <el-table-column prop="prodName" label="商品名称" />
              <el-table-column prop="prodPrice" label="商品价格" />
              <el-table-column prop="buyNum" label="购买数量" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="onDeleteProInfo(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div>总价：{{ totalAmount }}</div>
          </div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmitAddOrder()">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  getOrderListService,
  getProInfoListService,
  addOrderService,
  getDictListService,
} from "../api/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const tableData = ref([]);
const searchData = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
  status: null,
  type: null,
});
const total = ref(0);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ProInfoList = ref([]);
const form = ref({
  buyNum: null,
  infoId: null,
});
const orderTypeList = ref([]);
const userId = ref(0);
//导出
const onExportOrder = () => {
  let url = "http://localhost:9021/user/order/exportOrderList/" + userId.value;
  window.open(url);
};

const formatter = (row: any) => {
  let name = "未知";
  orderTypeList.value.forEach((item: any) => {
    if (item.dictValue == row.orderType) {
      name = item.dictName;
    }
  });
  console.log("name", name);
  return name;
};
//查看订单详情
const handleViewOrder = (row: any) => {
  console.log("handleViewOrder", row);
};

//总价
const totalAmount = ref(0);
//添加订单
const buyInfoList = ref([]);

const onAddOrder = () => {
  buyInfoList.value = [];
  form.value = {
    infoId: null,
    buyNum: 0,
  };
  totalAmount.value = 0;
  dialogFormVisible.value = true;
};

const addProdInfo = () => {
  ProInfoList.value.forEach((item) => {
    if (item.infoId === form.value.infoId) {
      item.buyNum = form.value.buyNum;
      buyInfoList.value.push(item);
    }
  });
  //动态计算订单总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//删除新增弹框里选择的商品
const onDeleteProInfo = (row: any) => {
  console.log("onDeleteProInfo", row);
  buyInfoList.value.forEach((item, index) => {
    if (item.infoId === row.infoId) {
      buyInfoList.value.splice(index, 1);
    }
  });
  //动态计算订单总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//添加方法
const onSubmitAddOrder = () => {
  addOrderService(buyInfoList.value).then((res) => {
    if (res.data.code == 200) {
      console.log("res", res);
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      getOrderList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchData.value.pageSize = val;
  getOrderList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchData.value.pageNum = val;
  getOrderList();
};

const getOrderList = () => {
  getOrderListService(searchData.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  getOrderList();
  getProInfoListService().then((res) => {
    if (res.data.code == 200) {
      ProInfoList.value = res.data.data;
    }
  });
  getDictListService(4).then((res) => {
    if (res.data.code == 200) {
      orderTypeList.value = res.data.data;
    }
  });
  //获取用户Id
  let u = sessionStorage.getItem("user");
  let user = JSON.parse(u);
  userId.value = user.userId;
});
</script>

<style scoped></style>
